package com.tehui.activity.impl;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.activity.BaseActivity;
import com.tehui.adapter.CommodityListAdapter;
import com.tehui.bean.BrandData;
import com.tehui.bean.FavoriteData;
import com.tehui.global.Global;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


//收藏夹

public class FavoriteActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar            toolbar;
    @BindView(R.id.lv)
    ListView           lv;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;
    @BindView(R.id.gv)
    GridView           gv;
    @BindView(R.id.scroll)
    ScrollView         scroll;
    @BindView(R.id.tvNetError)
    TextView           tvNetError;
    @BindView(R.id.btnNet)
    Button             btnNet;
    @BindView(R.id.llNet)
    LinearLayout       llNet;
    @BindView(R.id.loveMore)
    RelativeLayout     loveMore;
    @BindView(R.id.tvEdit)
    TextView           tvEdit;
    @BindView(R.id.tools)
    LinearLayout       tools;
    @BindView(R.id.all)
    TextView           all;
    @BindView(R.id.delete)
    TextView           delete;
    @BindView(R.id.cancel)
    TextView           cancel;
    @BindView(R.id.empty)
    TextView           empty;
    private List<FavoriteData.FavoriteDataBean> favoriteDatas;
    private List<BrandData.ResultBean>          result;
    private Timer                               timer;
    private boolean                             ischoes;
    private CommodityListAdapter                commodityListAdapter;
    private MyAdapter                           myAdapter;

    @Override
    public void initActivityData() {
        super.initActivityData();
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        lv.setDivider(null);//去除listview的下划线

        getServre();

        //相似物品
        initSimilarData();

        //下拉刷新
        initSwipe();

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_favorite;
    }

    @Override
    public void initViewListener() {
        tvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tools.setVisibility(View.VISIBLE);
                ischoes = true;
            }
        });

        btnNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getServre();
            }
        });


        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(UiUtils.getContext(), CommodityActivity.class);
                intent.putExtra("text", result.get(position).D_title);//标题
                intent.putExtra("id", result.get(position).GoodsID);//商品id
                intent.putExtra("url", result.get(position).discountLink);//优惠卷连接
                intent.putExtra("pic", result.get(position).Pic);//图
                intent.putExtra("quan", result.get(position).Quan_receive);//已领券
                intent.putExtra("num", result.get(position).Sales_num);//购买数
                intent.putExtra("time", result.get(position).Quan_time);//过期时间
                intent.putExtra("quanPrice", result.get(position).Quan_price);//优惠卷金额
                intent.putExtra("orgPrice", result.get(position).Org_Price);//原价
                intent.putExtra("price", result.get(position).Price + "");//券后价
                intent.putExtra("cid", result.get(position).Cid + "");
                intent.putExtra("IsTmall", result.get(position).IsTmall);
                intent.putExtra("Commission", result.get(position).Commission_jihua);
                intent.putExtra("quanid", result.get(position).Quan_id);
                jumpToActivity(intent);
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (ischoes) {
                    FavoriteData.FavoriteDataBean favoriteDataBean = favoriteDatas.get(position);
                    boolean isClick = favoriteDataBean.isClick;
                    if (isClick) {
                        favoriteDataBean.setClick(false);
                    } else {
                        favoriteDataBean.setClick(true);
                    }
                    myAdapter.notifyDataSetChanged();
                } else {
                    String goodsId = favoriteDatas.get(position).GoodsId;
                    Intent intent = new Intent();
                    intent.putExtra("isFromFavorite", true);
                    intent.putExtra("goodsId", goodsId);
                    intent.setClass(FavoriteActivity.this, CommodityActivity.class);
                    jumpToActivity(intent);
                }
            }
        });
    }

    private void initSwipe() {
        swipe.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light);
        swipe.setRefreshing(true);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe.setRefreshing(true);
                getServre();
            }
        });
    }

    public void getServre() {
        if (!UiUtils.isNetworkAvailable()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    scroll.setVisibility(View.GONE);
                    llNet.setVisibility(View.VISIBLE);
                    swipe.setRefreshing(false);
                }
            }, 1500);
            return;
        } else {
            llNet.setVisibility(View.GONE);
            scroll.setVisibility(View.VISIBLE);
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendTimeOutMsg();
            }
        }, Global.TIME_LIMIT);

        String openId = PrefUtils.getString("openId", "");
        OkGo.post(Global.URL_GETFAVORITE).tag(this).params("OpenId", openId).cacheKey("cacheKey").cacheMode
                (CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                parseJson(s);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
            }
        });
    }

    //网络超时处理
    private void sendTimeOutMsg() {
        OkGo.getInstance().cancelTag(this);
        UiUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                scroll.setVisibility(View.GONE);
                llNet.setVisibility(View.VISIBLE);
                tvNetError.setText("网络连接超时!");
                swipe.setRefreshing(false);
            }
        });
    }

    //解析收藏
    private void parseJson(String s) {
        FavoriteData favoriteData = JSON.parseObject(s, FavoriteData.class);
        favoriteDatas = favoriteData.favoriteData;
        timer.cancel();
        myAdapter = new MyAdapter();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loveMore.setVisibility(View.VISIBLE);
                if (favoriteDatas.size() == 0) {
                    empty.setVisibility(View.VISIBLE);
                } else {
                    empty.setVisibility(View.GONE);
                    lv.setAdapter(myAdapter);
                    lv.setVisibility(View.VISIBLE);
                }
                swipe.setRefreshing(false);
            }
        }, 1000);
    }

    //相似物品
    private void initSimilarData() {

        OkGo.get(Global.URL_SIMILAR).tag(this).cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT).execute
                (new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                //解析
                if (s.equals("-1")) {
                } else {
                    parseJsons(s);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
            }
        });
    }

    //解析相似物品
    private void parseJsons(String s) {
        BrandData brandData = JSON.parseObject(s, BrandData.class);
        result = brandData.result;
        commodityListAdapter = new CommodityListAdapter(result);
        gv.setAdapter(commodityListAdapter);
        scroll.setVisibility(View.VISIBLE);
        swipe.setRefreshing(false);
    }

    @OnClick({R.id.all, R.id.delete, R.id.cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.all:
                if (favoriteDatas != null) {
                    for (FavoriteData.FavoriteDataBean favoriteData : favoriteDatas) {
                        favoriteData.setClick(true);
                    }
                    myAdapter.notifyDataSetChanged();
                }

                break;
            case R.id.delete:
                String gId = "";
                ArrayList<FavoriteData.FavoriteDataBean> favoriteDataBeen = new ArrayList<>();
                for (FavoriteData.FavoriteDataBean favoriteData : favoriteDatas) {
                    if (favoriteData.isClick) {
                        favoriteDataBeen.add(favoriteData);
                        String goodsId = favoriteData.GoodsId;
                        gId = gId + "," + goodsId;
                    }
                }

                if (favoriteDataBeen.size() == 0) {
                    UiUtils.toast("没有选中商品!");
                    return;
                }

                String openId = PrefUtils.getString("openId", "");

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("openId", openId);
                    jsonObject.put("goodsId", gId);
                    String s = jsonObject.toString();

                    setServre(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                favoriteDatas.removeAll(favoriteDataBeen);
                if (favoriteDatas.size() == 0) {
                    lv.setVisibility(View.GONE);
                    empty.setVisibility(View.VISIBLE);
                } else {
                    myAdapter.notifyDataSetChanged();
                }
                tools.setVisibility(View.GONE);
                ischoes = false;
                break;
            case R.id.cancel:
                tools.setVisibility(View.GONE);
                ischoes = false;
                if (favoriteDatas != null) {
                    for (FavoriteData.FavoriteDataBean favoriteData : favoriteDatas) {
                        favoriteData.setClick(false);
                    }
                    myAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    public void setServre(String servre) {
        OkGo.post("http://dl.21tehui.com/Favorite/batchDelete.html").tag(this).params("str", servre)
                .cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String info = (String) jsonObject.get("info");

                    if (info.equals("1")) {
                        UiUtils.toast("删除成功");
                    } else if (info.equals("-1")) {
                        UiUtils.toast("删除失败,请稍候重试!");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
            }
        });
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return favoriteDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(FavoriteActivity.this, R.layout.item_favorite_layout, null);
                holder = new ViewHolder();
                //holder.btn = (Button) convertView.findViewById(R.id.btnLook);
                holder.img = (ImageView) convertView.findViewById(R.id.img);
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
                holder.num = (TextView) convertView.findViewById(R.id.num);
                holder.money = (TextView) convertView.findViewById(R.id.money);
                holder.item = (RelativeLayout) convertView.findViewById(R.id.item);
                holder.salenum = (TextView) convertView.findViewById(R.id.salenum);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvTitle.setText(favoriteDatas.get(position).Title);
            holder.money.setText("¥" + favoriteDatas.get(position).Price);
            holder.num.setText("优惠券¥" + favoriteDatas.get(position).QuanPrice);
            holder.salenum.setText("销量" + favoriteDatas.get(position).SaleNum);

            Glide.with(FavoriteActivity.this).load(favoriteDatas.get
                    (position).PicUrl).apply(options).into(holder.img);

            boolean isClick = favoriteDatas.get(position).isClick;

            if (isClick) {
                holder.item.setBackgroundResource(R.drawable.favorite_bg_shape);
            } else {
                holder.item.setBackgroundResource(0);
            }
            return convertView;
        }
    }

    public static class ViewHolder {
        TextView       tvTitle;
        ImageView      img;
        TextView       money;
        TextView       num;
        TextView       salenum;
        RelativeLayout item;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
